package com.youyun56.car;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import com.j3.db.ConnectionManager;
import com.j3.sql.BatchFunc;
import com.j3.sql.GridUtils;
import com.youyun56.gps.sms.PathConfig;

public class CreateCarSaveTable {
    private final static Logger log = Logger.getLogger(CreateCarSaveTable.class);

    public CreateCarSaveTable() throws Exception {

        initDB();
    }

    private void initDB() throws Exception {
        Properties props = new Properties();
        props.load(new FileInputStream(PathConfig.ROOT + File.separator + "config.properties"));
        DataSource bds = BasicDataSourceFactory.createDataSource(props);
        ConnectionManager.registerDataSource("gps", bds);
        ConnectionManager.setDefaultDataSourceName("gps");
    }

    public void create() throws SQLException {
        GridUtils grid = new GridUtils();
        grid.init("select * from car");
        BatchFunc fun = new BatchFunc();
        List<String> sqls = new ArrayList<String>();
        while (grid.next()) {
            sqls.clear();
            int id = grid.getInt("id");
            String usualLine = grid.get("usualLine");
            if (usualLine != null && usualLine.trim().length() > 0) {
                String[] lines = usualLine.split(",");
                for (String line : lines) {
                    sqls.add(String.format("delete from city%d_save_line where car_id = %d;", Integer.parseInt(line), id));
                    sqls.add(String.format("insert into city%d_save_line(car_id) values (%d);", Integer.parseInt(line), id));
                }
            } else {
                sqls.add(String.format("update car set usualLine = '0' where id = %d;", id));
                sqls.add(String.format("delete from city0_save_line where car_id = %d;", id));
                sqls.add(String.format("insert into city0_save_line(car_id) values (%d);", id));
            }
            try {
                fun.doBatch(sqls);
            }
            catch (Exception e) {
                log.info(sqls, e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        System.setProperty("server", "sms");
        DOMConfigurator.configure(PathConfig.ROOT + "/log4j.xml");
        CreateCarSaveTable c = new CreateCarSaveTable();
        c.create();
    }

}
